package dhm.com.hpx.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.hpx.R;
import dhm.com.hpx.adapter.MineCardAdapter;
import dhm.com.hpx.base.BaseActivity;
import dhm.com.hpx.base.Presenter.PressenterImpl;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.base.netWork.LoginContract;
import dhm.com.hpx.entity.Bean;
import dhm.com.hpx.entity.CollectUserBean;
import dhm.com.hpx.entity.DynamicListaBean;
import dhm.com.hpx.entity.FabulousVideoBean;
import dhm.com.hpx.entity.FavoriteArticleBean;
import dhm.com.hpx.entity.GetUserInfoBean;
import dhm.com.hpx.utils.SpUtils;
import dhm.com.hpx.utils.mapapi.Util;

public class MinecardActivity extends BaseActivity implements LoginContract.IView, IWXAPIEventHandler {

    @BindView(R.id.guanzhu)
    Button guanzhu;
    @BindView(R.id.todaa)
    LinearLayout todaa;
    @BindView(R.id.more)
    ImageView more;
    @BindView(R.id.recy)
    RecyclerView recy;

    private PressenterImpl pressenter;
    private String uid;
    private GetUserInfoBean getUserInfoBean;
    private DynamicListaBean dynamicListaBean;
    private int delposition;
    private MineCardAdapter adapter;
    private String uids;

    @Override
    protected int getLayout() {
        return R.layout.activity_minecard;
    }

    @SuppressLint("NewApi")
    @Override
    protected void initView() {
        ButterKnife.bind(this);

        pressenter=new PressenterImpl();
        pressenter.attachView(this);

        getWindow().setStatusBarColor(getResources().getColor(R.color.card));

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //修改为深色，因为我们把状态栏的背景色修改为主题色白色，默认的文字及图标颜色为白色，导致看不到了。
//            getWindow().getDecorView().setSystemUiVisibility(View.);

            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    |View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
            decorView.setSystemUiVisibility(uiOptions);

        }
        uids = SpUtils.getString(this, "uid");

        uid = getIntent().getStringExtra("uid");
        api = WXAPIFactory.createWXAPI(this, Constant.Wx_APP_ID,false);
        if (uid.equals(uids)){
            guanzhu.setVisibility(View.GONE);
            more.setVisibility(View.VISIBLE);
            todaa.setVisibility(View.VISIBLE);
        }else {
            String is_follow = getIntent().getStringExtra("is_follow");
            if (is_follow.equals("1")){
                isfavorite=1;
                guanzhu.setBackgroundResource(R.drawable.back_quan);
                guanzhu.setText("已关注");
                guanzhu.setTextColor(Color.parseColor("#999999"));
            }else {
                isfavorite=0;
                guanzhu.setText("关注");
                guanzhu.setTextColor(getResources().getColor(R.color.white));
                guanzhu.setBackgroundResource(R.drawable.shape_login);
            }
            guanzhu.setVisibility(View.VISIBLE);
            more.setVisibility(View.GONE);
            todaa.setVisibility(View.GONE);
            Map<String,String> map=new HashMap<>();
            map.put("token",Constant.TOKEN);
            map.put("user_id",uid);
            map.put("cover_user_id", uids);
            map.put("browse_type","1");

            pressenter.sendMessage(MinecardActivity.this,Constant.visitorrecordadd,map,Bean.class);

        }

        LinearLayoutManager manager=new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy.setLayoutManager(manager);

        adapter = new MineCardAdapter(this,uid);
        recy.setAdapter(adapter);
        adapter.setdeleteClick(new MineCardAdapter.OnClick() {
            @Override
            public void item(int posttion, View view) {
                delposition = posttion;
                setBackgroundAlpha(0.5f);
                popWindows.showAsDropDown(view);
            }
        });
        adapter.setaddClick(new MineCardAdapter.OnIntentClick() {
            @Override
            public void item(int type) {
                Map<String,String> map;
                switch (type) {
                    case 1:
                        map=new HashMap<>();
                        map.put("token",Constant.TOKEN);
                        map.put("uid",uid);
                        pressenter.sendMessage(MinecardActivity.this,Constant.dynamic_list, map,DynamicListaBean.class);
                        break;
                    case 2:
                        map=new HashMap();
                        map.put("token", Constant.TOKEN);
                        map.put("uid",uid);
                        map.put("page","1");

                        pressenter.sendMessage(MinecardActivity.this,Constant.listVideoQuery_fablulous,map, FabulousVideoBean.class);
                        break;
                    case 3:
                        map=new HashMap();
                        map.put("token", Constant.TOKEN);
                        map.put("uid",uid);
                        map.put("page","1");
                        pressenter.sendMessage(MinecardActivity.this,Constant.listArticlesQuery,map, FavoriteArticleBean.class);
                        break;
                    default:
                }

            }
        });

    }

    @Override
    protected void initData() {

    }


    @Override
    protected void onResume() {
        super.onResume();

        Map<String, String> map = new HashMap<>();
        map.put("token", Constant.TOKEN);
        map.put("uid", uid);
        pressenter.sendMessage(MinecardActivity.this, Constant.get_userinfo, map, GetUserInfoBean.class);

        showPopwindow();
        showpopWindows();

    }

    private int isfavorite=0;

    int page=1;

    @SuppressLint("NewApi")
    @OnClick({R.id.back,R.id.guanzhu,R.id.todaa, R.id.more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.guanzhu:
                if (isfavorite==0){
                    Map<String,String> map=new HashMap<>();
                    map.put("token",Constant.TOKEN);
                    map.put("type","3");
                    map.put("uid",uids);
                    map.put("id",uid);
                    pressenter.sendMessage(MinecardActivity.this,Constant.add,map,Bean.class);
                }else {
                    Map<String,String> map=new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("uid",uids);
                    map.put("page",page+"");
                    pressenter.sendMessage(this,Constant.listUserQuery,map, CollectUserBean.class);
                }

                break;
            case R.id.todaa:
                Intent intent=new Intent(this,DynamicActivity.class);
                startActivity(intent);
                break;
            case R.id.more:
                setBackgroundAlpha(0.5f);
                popWindow.showAsDropDown(view);
                break;
                default:
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void requesta(Object data) {
        if (data instanceof GetUserInfoBean){
            getUserInfoBean = (GetUserInfoBean) data;
            if (getUserInfoBean.getCode()!=1){
                Toast.makeText(this, "暂无此用户信息", Toast.LENGTH_SHORT).show();
                return;
            }
            Map<String,String> map=new HashMap<>();
            adapter.setGetUserInfoBean(getUserInfoBean);
            map.put("token",Constant.TOKEN);
            map.put("uid",uid);
            pressenter.sendMessage(this,Constant.dynamic_list, map,DynamicListaBean.class);

        }else if (data instanceof DynamicListaBean){
            dynamicListaBean = (DynamicListaBean) data;
            if (dynamicListaBean.getCode()==1){
                recy.setVisibility(View.VISIBLE);
                for (int i = 0; i < dynamicListaBean.getData().size(); i++) {
                    dynamicListaBean.getData().get(i).setImage(getUserInfoBean.getData().getHeadsmall());
                    dynamicListaBean.getData().get(i).setNick(getUserInfoBean.getData().getUser_nickname());
                }

                adapter.setList(dynamicListaBean.getData());
            }
        }else if (data instanceof Bean){
            Bean bean= (Bean) data;

            if (bean.getCode()==1){
                if (bean.getMessage().equals("访客记录添加成功")){

                }else if (bean.getMessage().equals("已经收藏")){
                    isfavorite=1;
                    guanzhu.setBackgroundResource(R.drawable.back_quan);
                    guanzhu.setText("已关注");
                    guanzhu.setTextColor(Color.parseColor("#999999"));
                }else if (bean.getMessage().equals("收藏成功")){
                    isfavorite=1;
                    guanzhu.setBackgroundResource(R.drawable.back_quan);
                    Toast.makeText(this, "关注成功", Toast.LENGTH_SHORT).show();
                    guanzhu.setText("已关注");
                    guanzhu.setTextColor(Color.parseColor("#999999"));
                }else if (bean.getMessage().equals("取消成功")){
                    isfavorite=0;
                    Toast.makeText(this, "取消关注成功", Toast.LENGTH_SHORT).show();
                    guanzhu.setText("关注");
                    guanzhu.setTextColor(getResources().getColor(R.color.white));
                    guanzhu.setBackgroundResource(R.drawable.shape_login);
                }else if (bean.getMessage().equals("已经收藏")){
                    isfavorite=1;
                    guanzhu.setBackgroundResource(R.drawable.back_quan);
                    guanzhu.setText("已关注");
                    guanzhu.setTextColor(Color.parseColor("#999999"));
                } else {
                    dynamicListaBean.getData().remove(delposition);
                    adapter.setList(dynamicListaBean.getData());
                }
            }
        }else if (data instanceof FabulousVideoBean){
            FabulousVideoBean fabulousVideoBean= (FabulousVideoBean) data;
            if (fabulousVideoBean.getCode()==1){
                recy.setVisibility(View.VISIBLE);
                adapter.setList2(fabulousVideoBean.getData());
            }


        }else if (data instanceof FavoriteArticleBean){
            FavoriteArticleBean favoriteArticleBean= (FavoriteArticleBean) data;
            if (favoriteArticleBean.getCode()==1){
                recy.setVisibility(View.VISIBLE);
                adapter.setList3(favoriteArticleBean.getData());
            }
        }else if (data instanceof CollectUserBean){
            CollectUserBean collectUserBean= (CollectUserBean) data;
            page++;
            if (collectUserBean.getCode()==1){
                boolean iscontinue=true;
                for (int i = 0; i < collectUserBean.getData().size(); i++) {
                    if (uid.equals(collectUserBean.getData().get(i).getUserId()+"")){
                        iscontinue=false;
                        page=1;
                        Map<String,String> map=new HashMap<>();
                        map.put("token",Constant.TOKEN);
                        map.put("uid",uids);
                        map.put("type","3");
                        map.put("cid",collectUserBean.getData().get(i).getFavoriteId()+"");
                        pressenter.sendMessage(MinecardActivity.this,Constant.cancel,map,Bean.class);
                    }
                }
                if (iscontinue){
                    Map<String,String> map=new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("uid",uids);
                    map.put("page",page+"");
                    pressenter.sendMessage(this,Constant.listUserQuery,map, CollectUserBean.class);
                }

            }

        }
    }

    @Override
    public void fail(String error) {

    }
    private IWXAPI api;
    private int mTargetScene = SendMessageToWX.Req.WXSceneSession;
    private PopupWindow popWindow;
    private void showPopwindow() {
        View popView = View.inflate(this,R.layout.popup_card, null);
        TextView share = popView.findViewById(R.id.share);
        TextView edit = popView.findViewById(R.id.edit);

        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
                miniProgramObj.webpageUrl = "http://www.qq.com"; // 兼容低版本的网页链接
                miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
                miniProgramObj.userName = "gh_adcea7f82ee9";     // 小程序原始id
                miniProgramObj.path = "/pages/sharePage/sharePage?uid="+uid+"&mobile="+getUserInfoBean.getData().getMobile();            //小程序页面路径；对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"
                WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
                msg.title = "个人名片";                    // 小程序消息title
                msg.description = "查看"+getUserInfoBean.getData().getUser_nickname()+"的名片";               // 小程序消息desc
                Bitmap thumbBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.logo);
                msg.thumbData = Util.bmpToByteArray(thumbBmp, true);
//                msg.thumbData = getThumb();                      // 小程序消息封面图片，小于128k

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("miniProgram");
                req.message = msg;
                req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前只支持会话
                api.sendReq(req);

                popWindow.dismiss();

            }
        });
        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MinecardActivity.this,MyinfoActivity.class);
                startActivity(intent);
                popWindow.dismiss();
            }
        });


        popWindow = new PopupWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popWindow.setFocusable(true);
        popWindow.setTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失

        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
            }
        });

    }


    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }



    private PopupWindow popWindows;
    private void showpopWindows() {
        View popView = View.inflate(this,R.layout.popup_del, null);
        TextView del = popView.findViewById(R.id.del);
        TextView edit = popView.findViewById(R.id.edit);

        del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Map<String,String> map=new HashMap<>();
                map.put("token",Constant.TOKEN);
                map.put("uid",uid);
                map.put("dynamic_id",dynamicListaBean.getData().get(delposition).getDynamic_id()+"");
                pressenter.sendMessage(MinecardActivity.this,Constant.dynamic_del,map, Bean.class);
                popWindows.dismiss();
            }
        });

        popWindows = new PopupWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popWindows.setFocusable(true);
        popWindows.setTouchable(true);
        popWindows.setBackgroundDrawable(new BitmapDrawable());
        popWindows.setOutsideTouchable(true);// 设置允许在外点击消失

        popWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
            }
        });

    }


    @Override
    public void onReq(BaseReq baseReq) {
        Toast.makeText(this, baseReq.transaction, Toast.LENGTH_SHORT).show();
    }
    final String TAG="微信分享结果";
    @Override
    public void onResp(BaseResp resp) {
        Log.d(TAG, "onPayFinish, errCode = " + resp.errCode);
        Toast.makeText(this, resp.errCode+resp.errStr, Toast.LENGTH_SHORT).show();
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {

            switch (resp.errCode) {
                case 0://支付成功
                    Toast.makeText(this, "分享成功", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "onResp: resp.errCode = 0   分享成功");
                    break;
                case -1://错误，可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
                    Toast.makeText(this, "分享错误" + resp.errCode, Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "onResp: resp.errCode = -1  分享错误");
                    break;
                case -2://用户取消，无需处理。发生场景：用户不支付了，点击取消，返回APP。
                    Log.d(TAG, "onResp: resp.errCode = -2  用户取消");
                    Toast.makeText(this, "用户取消" + resp.errCode, Toast.LENGTH_SHORT).show();
                    break;
                default:
            }

            finish();//这里需要关闭该页面
        }
    }
}
